//
//  HDWeixinHelper.m
//  leek-weixin_Example
//
//  Created by 吴非 on 2022/1/21.
//  Copyright © 2022 懒虫. All rights reserved.
//

#import "HDWeixinHelper.h"

//#import <WechatOpenSDK/WXApi.h>
#import "WXApi.h"


@interface HDWeixinHelper()<WXApiDelegate>

// 结果处理
@property (nonatomic, copy, readwrite) HDWeixinHelperCompletion handleCompletion;

/// 应用ID
@property (nonatomic, copy, readwrite) NSString* wxId;
/// 申请权限
@property (nonatomic, copy, readwrite) NSString* wxAuthScope;
/// 微信开发者Universal Link
@property (nonatomic, copy, readwrite) NSString* wxUniversalLink;

// 授权登录
@property (nonatomic, weak, nullable) id <HDWeixinAuthorizedLoginDelegate> delegateAuthorized;

// 用户支付
@property (nonatomic, weak, nullable) id <HDWeixinPaymentDelegate> delegatePayment;

// 用户分享
@property (nonatomic, weak, nullable) id <HDWeixinSharingDelegate> delegateSharing;

// 小程序
@property (nonatomic, weak, nullable) id <HDWeixinSmallRoutineDelegate> delegateSmallRoutine;

// 跳转客服
@property (nonatomic, weak, nullable) id <HDWeixinCustomerServiceDelegate> delegateCustomerService;

@end

@implementation HDWeixinHelper

// 单例
+(instancetype)defaultService {
    static HDWeixinHelper *sharedUnique = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedUnique = [[HDWeixinHelper alloc] init];
    });
    return sharedUnique;
}

/// 查看当前版本
-(NSString *)wxVersion {
    return [WXApi getApiVersion];
}

/// 打印日志
-(void)wxLogger {
    
    [WXApi startLogByLevel:WXLogLevelDetail logBlock:^(NSString *log) {
        NSLog(@"日志WeChatSDK: %@", log);
    }];

    //调用自检函数
    [WXApi checkUniversalLinkReady:^(WXULCheckStep step, WXCheckULStepResult* result) {
        NSLog(@"调用自检函数 ==> %@, %u, %@, %@", @(step), result.success, result.errorInfo, result.suggestion);
    }];
}

// MARK: - 配置参数

+ (void)rendering:(NSString*)appId universalLink:(NSString *)universalLink {
    // 加载配置
    [[HDWeixinHelper defaultService] setWxId:appId];
    [[HDWeixinHelper defaultService] setWxUniversalLink:universalLink];
    // 注册微信
    [WXApi registerApp:appId universalLink:universalLink];
}

// MARK: - 授权登录
/**
 文档地址： https://developers.weixin.qq.com/doc/oplatform/Mobile_App/WeChat_Login/Development_Guide.html
 第一步获取：code
 第二步获取：https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
 获取接口调用凭证： access_token
 过期刷新：https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN
 */

- (void)authorizedLogin:(NSString*)scope
               targetVC:(UIViewController*)tmpVC
         completeHandle:(id<HDWeixinAuthorizedLoginDelegate>)handle {
    // 结果处理
    [self setDelegateAuthorized:handle];
    // 应用包名
    NSString *kBundleId = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
    // 授权信息
    NSString *kAuthScope = @"snsapi_message,snsapi_userinfo,snsapi_friend,snsapi_contact";
    
    SendAuthReq* req = [[SendAuthReq alloc] init];
    req.scope =  @"snsapi_userinfo"; // kAuthScope;
    req.state = kBundleId;
    req.openID = [[HDWeixinHelper defaultService] wxId];
    
    [WXApi sendAuthReq:req viewController:tmpVC delegate:self completion:^(BOOL success) {
        NSLog(@"SDK发送登录授权操作[%d]", success);
    }];
}

// MARK: - 快捷分享

- (void)shareImageData:(NSData *)imageData
            ThumbImage:(UIImage *)thumbImage
               InScene:(NSInteger)scene
        completeHandle:(id<HDWeixinSharingDelegate>)handle {
    
    [self setDelegateSharing:handle];
    
    WXImageObject *byObjc = [WXImageObject object];
    byObjc.imageData = imageData;
    
    WXMediaMessage *byMessage = [WXMediaMessage message];
    [byMessage setMediaObject:byObjc];
    [byMessage setThumbImage:thumbImage];
    
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    [req setMessage:byMessage];
    [req setScene:(int)scene];
    [req setBText:NO];
    
    [WXApi sendReq:req completion:^(BOOL success) {
        NSLog(@"SDK发送分享图片操作[%d]", success);
    }];

}

/*分享链接*/
- (void)shareLinkURL:(NSString *)urlString
               Title:(NSString *)title
         Description:(NSString *)descr
          ThumbImage:(UIImage *)thumbImage
             InScene:(NSInteger)scene
      completeHandle:(id<HDWeixinSharingDelegate>)handle {
    
    [self setDelegateSharing:handle];
    
    WXWebpageObject *byObjc = [WXWebpageObject object];
    byObjc.webpageUrl = urlString;

    WXMediaMessage *byMessage = [WXMediaMessage message];
    [byMessage setTitle:title];
    [byMessage setDescription:descr];
    [byMessage setMediaObject:byObjc];
    [byMessage setThumbImage:thumbImage];
    
    SendMessageToWXReq* byReqData = [[SendMessageToWXReq alloc] init];
    [byReqData setMessage:byMessage];
    [byReqData setScene:(int)scene];
    [byReqData setBText:NO];


    [WXApi sendReq:byReqData completion:^(BOOL success) {
        NSLog(@"SDK发送分享链接操作[%d]", success);
    }];
}

// 跳转客服
-(void)contactCustomerServiceURL:(NSString *)urlString
                        corpCode:(NSString *)corpId
                  completeHandle:(id<HDWeixinCustomerServiceDelegate>)handle {
    
    [self setDelegateCustomerService:handle];
    
    WXOpenCustomerServiceReq *req = [[WXOpenCustomerServiceReq alloc] init];
    req.corpid = corpId;    // 企业ID
    req.url = urlString;    // 客服URL
    [WXApi sendReq:req completion:^(BOOL success) {
        NSLog(@"SDK发送分享链接操作[%d]", success);
    }];
}

/*分享小程序*/
/*
  #=> 拉起的小程序的username # gh_d43f693ca31f@app
  #=> 拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
  #=> WXMiniProgramTypeRelease #  0是正式版，1是开发版，2是体验版
 */
-(void)shareLinkSmallRoutine:(NSString *)strUsername
                     pathURL:(NSString *)strPath
                 programType:(NSUInteger)miniProgramType
              completeHandle:(id<HDWeixinSmallRoutineDelegate>)handle {
    
    [self setDelegateSmallRoutine:handle];
    
    WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
    launchMiniProgramReq.userName = strUsername;
    launchMiniProgramReq.path = strPath;
    launchMiniProgramReq.miniProgramType = miniProgramType;
    
    [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
        NSLog(@"SDK发送小程序链接操作[%d]", success);
    }];
}


// MARK: - 快捷支付
/// {"code":"00","message":"处理成功","data":{"result":"{\"sign\":\"3B643891D6E804889DD77BED28F141F5\",\"prepayId\":\"wx081509269104329f5af375f772f3aa0000\",\"partnerId\":\"1620154634\",\"appId\":\"wxf0a21e8ecb80ea7f\",\"packageValue\":\"Sign=WXPay\",\"timeStamp\":\"1644304166\",\"nonceStr\":\"NhtOvAV6TOhrPJoY\"}"},"others":null}
-(void)payWith:(HDPayOrderModel*)infor completeHandle:(id<HDWeixinPaymentDelegate>)handle {
    
    [self setDelegatePayment:handle];
    
    if([WXApi isWXAppInstalled]){
        //调起微信支付
        PayReq* req             = [[PayReq alloc] init];
        req.openID              = infor.appid;
        req.partnerId           = infor.partnerid;
        req.prepayId            = infor.prepayid;
        req.nonceStr            = infor.noncestr;
        req.timeStamp           = infor.timestamp;
        req.package             = infor.package;
        req.sign                = infor.sign;
        [WXApi sendReq:req completion:^(BOOL success) {
            NSLog(@"%d", success);
        }];
    }else{
        if ([handle respondsToSelector:@selector(hdWeixinPaymentResponseHandle:)]) {
            [handle hdWeixinPaymentResponseHandle:999];
        }
    }
}
// 发起支付集合版
-(void)payWithParameter:(NSString*)json completeHandle:(HDWeixinHelperCompletion)handleBlock {
    
    [self setHandleCompletion:handleBlock];
    
    NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
    NSError *tmpError;
    NSDictionary *infor = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&tmpError];
    // 解析错误
    if (nil != tmpError) {
        !handleBlock ?: handleBlock(998);
        return;
    }
    
    if([WXApi isWXAppInstalled]){
        //调起微信支付
        PayReq* req             = [[PayReq alloc] init];
        req.openID              = [infor objectForKey:@"appId"];
        req.partnerId           = [infor objectForKey:@"partnerId"];
        req.prepayId            = [infor objectForKey:@"prepayId"];
        req.nonceStr            = [infor objectForKey:@"nonceStr"];
        req.timeStamp           = [[infor objectForKey:@"timeStamp"] intValue];
        req.package             = [infor objectForKey:@"packageValue"];
        req.sign                = [infor objectForKey:@"sign"];
        [WXApi sendReq:req completion:^(BOOL success) {
            NSLog(@"%d", success);
        }];
    }else{
        !handleBlock ?: handleBlock(999);
    }

}
// MARK: - 回调处理

- (BOOL)handleOpenURL:(NSURL *)openURL {
    return  [WXApi handleOpenURL:openURL delegate:self];
}

- (BOOL)handleUserActivity:(NSUserActivity *)userActivity {
    return [WXApi handleOpenUniversalLink:userActivity delegate:self];
}



// MARK: - WXApiDelegate & 处理微信回调事件


/* 收到一个来自微信的请求，第三方应用程序处理完后调用sendResp向微信发送结果
 * 收到一个来自微信的请求，异步处理完成后必须调用sendResp发送处理结果给微信。
 * 可能收到的请求有GetMessageFromWXReq、ShowMessageFromWXReq等。
 * @param req 具体请求内容，是自动释放的
 */
- (void)onReq:(BaseReq*)req {
    // 分享处理
    if ([req isKindOfClass:[ShowMessageFromWXReq class]]){
        if (_delegateSharing
            && [_delegateSharing respondsToSelector:@selector(hdWeixinSharingShowMessageReq:)]) {
//            ShowMessageFromWXReq *showMessageReq = (ShowMessageFromWXReq *)req;
            [_delegateSharing hdWeixinSharingShowMessageReq: [NSDictionary new]];
        }
    }
    
    
}

/* 发送一个sendReq后，收到微信的回应
 * 收到一个来自微信的处理结果。调用一次sendReq后会收到onResp。
 * 可能收到的处理结果有SendMessageToWXResp、SendAuthResp等。
 * @param resp具体的回应内容，是自动释放的
 */
- (void)onResp:(BaseResp*)resp {
    // 支付处理
    if ([resp isKindOfClass:[PayResp class]]) {
        PayResp *payResp = (PayResp *)resp;
        [[self delegatePayment] hdWeixinPaymentResponseHandle:[payResp errCode]];
        !_handleCompletion ?: _handleCompletion([payResp errCode]);
        return;
    }
    
    // 分享处理
    if ([resp isKindOfClass:[SendMessageToWXResp class]]){
        [[self delegateSharing] hdWeixinSharingResponseHandle:[(SendMessageToWXResp *)resp errCode]];
        return;
    }
    
    // 跳转客服
    if ([resp isKindOfClass:[WXOpenCustomerServiceResp class]]){
        [[self delegateCustomerService] hdWeixinCustomerServiceHandle:[(WXOpenCustomerServiceResp *)resp errCode]];
        return;
    }
    
    // 小程序处理
    if ([resp isKindOfClass:[WXLaunchMiniProgramResp class]]){
        [[self delegateSmallRoutine] hdWeixinSmallRoutineHandle:[(WXLaunchMiniProgramResp *)resp extMsg]];
        return;
    }
    
    
    // 授权登录
    if ([resp isKindOfClass:[SendAuthResp class]]){
        SendAuthResp *authResp = (SendAuthResp *)resp;
        NSLog(@"微信授权回调信息 ==> code # %@", [authResp code]);
        NSLog(@"微信授权回调信息 ==> state # %@", [authResp state]);
        [[self delegateAuthorized] hdWeixinAuthorizedResponseHandle:[authResp code] error:[authResp errCode]];
        return;
    }
}


@end
